import axios from 'axios'
import Qs from 'qs'
import { Notification } from 'element-ui';
import util from './util'
import router from '../router'



class HttpRequest {
  constructor(baseUrl) {
    if (baseUrl) {
      this.baseUrl = baseUrl;
    } else {
      //如果是开发环境
      if(process.env.NODE_ENV=='development'){
        this.baseUrl = 'http://192.168.0.100:8885';
      }else{
        this.baseUrl="";
      }
    }
    console.log("开发环境:"+process.env.NODE_ENV+"  baseUrl:"+this.baseUrl);
    this.queue = {}
  }
  getInsideConfig(retype,app) {
    if (!retype) {
      retype = 'application/x-www-form-urlencoded'
    }
    let config = {
      baseURL: this.baseUrl,
      timeout: 10000,
      withCredentials: true,
      headers: {
        'Content-Type': retype,
        "token": util.getToken(),
      }
    }
    if(app){
      let appMenus = util.get("userInfo").appMenus;
      if(appMenus && appMenus.length>0){
        for(var i=0;i<appMenus.length;i++){
          if(appMenus[i].appCode==app){
            config.baseURL=appMenus[i].appUrl;
          }
        }
      }
    }
    return config
  }
  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
    }
  }

  interceptors(instance, ops) {

    let ref = this;
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        //  Spin.show() // 不建议开启，因为界面不友好
      }
      if (config.method == 'post' && config.headers['Content-Type'] == 'application/json') {
        config.data = JSON.stringify(config.data)
      }
      return config;
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
       return this.parseData(res);
    }, error => {
      let errorInfo = error.response;
      if (errorInfo && errorInfo.data) {
        if(errorInfo.data.code=="t001"){
          router.push('/login'); 
          return;
        }
        let errinfo = "error";
        if (errorInfo.data.errMsg) {
          errinfo = errorInfo.data.errMsg;
        } else {
          errinfo = JSON.stringify(errorInfo.data);
        }
        Notification.error({
          title: '错误',
          message: errinfo
        });
      } else {
        Notification.error({
          title: '错误',
          message: JSON.stringify(error.message)
        });
      }
      return Promise.reject(error)
    })
  }
  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }

  parseData(res){
    if (res.data && res.data.code && res.data.code != "200") {
      Notification.error({ 'title': '请求错误', 'message': res.data.errMsg })
      return Promise.reject(res)
    } else if (res.data && res.data.code && res.data.code == "200" && res.data.data) {
      return (res.data.data);
    }
    return res.data
  }

  // get 请求
  get(url,app) {
    const instance = axios.create()
    let options = Object.assign(this.getInsideConfig("",app), { 'method': 'GET', 'url': url })
    this.interceptors(instance, options)
    return instance(options)
  }
  // 请求json
  postJson(url, data,app) {
    const instance = axios.create()
    let reconfig = this.getInsideConfig('application/json',app)
    let options = Object.assign(reconfig, { 'data': data, 'url': url, 'method': 'POST' })
    this.interceptors(instance, options.url)
    return instance(options)
  }

  // post form
  post(url, data,app) {
    const instance = axios.create()
    let reconfig = this.getInsideConfig("",app)
    let options = Object.assign(reconfig, { 'data': Qs.stringify(data), 'url': url, 'method': 'POST' })
    this.interceptors(instance, options.url)
    return instance(options)
  }

  // post form 上传文件和表单
  postFormData(url, data,app) {
    const instance = axios.create()
    let reconfig = this.getInsideConfig("multipart/form-data",app)
    let param = null;
    if (data && !(data instanceof FormData)) {
      param = new FormData();
      for (var key in data) {
        param.append(key, data[key]);
      }
    } else {
      param = data;
    }
    let options = Object.assign(reconfig, { 'data': param, 'url': url, 'method': 'POST' })
    this.interceptors(instance, options.url)
    return instance(options)
  }


}
export default HttpRequest
